<template>
  <div>
    <div class="selector">
      <div class="classroom-select flex" v-if="showClassroom">
        <div class="select">
          <el-cascader
            v-if="isTargetBoost"
            v-model="selectedClass"
            :options="tbClassList"
            @change="changeTbClass"
          />
          <el-tree-select
            v-else
            v-model="classId"
            :data="classroomData"
            @change="changeClassroom"
          />
        </div>
      </div>
      <div class="date">
        <el-date-picker
          :disabled="currentTab === 'mastery-level'"
          v-model="selectTime"
          type="daterange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-value="defaultDateRange"
          :default-time="defaultTime"
          value-format="X"
          :shortcuts
        />
      </div>
    </div>
    <Teleport to="body">
      <PracticeTaskModal :task-type="4" v-model:visible="practiceVis" />
    </Teleport>
  </div>
</template>
<script setup>
import { ref, computed, watch, defineModel, onBeforeMount, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/stores'
import { postClassroomTree } from '@/apis'
import PracticeTaskModal from './publish-task/PracticeTaskModal.vue'

const props = defineProps({
  isKnowledge: Boolean,
  showClassroom: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['changeSubject'])

const authStore = useAuthStore()
const {
  // getUserInfoFun,
  userInfo,
  getClassListOfSubject,
  getTeachingInfo
} = authStore
const {
  /* tbSubjectListInLabelValue, */ nowGlobalSubjectId,
  selectedClass,
  nowGlobalStageId,
  nowGlobalRole,
  tbAdminAndTeachingClassList,
  classType,
  nowIsSmartRoomCode
} = storeToRefs(authStore)

const route = useRoute()

const currentTab = defineModel('currentTab')
const practiceVis = ref(false)
const classId = defineModel('classId')
// const subject = ref('')
const selectTime = defineModel('selectTime')
const currentGradeNum = defineModel('currentGradeNum')
const currentGradeId = defineModel('currentGradeId')

const classroomData = ref([])
const tbClassList = ref([])

// const subjectOptions = ref([])

const isTargetBoost = computed(
  () =>
    props.isKnowledge ||
    ['target-error-questions', 'personalize-target'].includes(route.name)
)

const findNodeIdById = (nodes, targetValue) => {
  console.log(nodes)
  for (let node of nodes) {
    console.log(node.value === targetValue)
    if (node.id) {
      return node.id
    }
    if (node.children) {
      const childResult = findNodeIdById(node.children, targetValue)
      if (childResult) {
        return childResult
      }
    }
  }
  return null
}
const changeClassroom = val => {
  currentGradeNum.value = findNodeIdById(classroomData.value, val)
}

function changeTbClass(classList) {
  console.log(classList)
  classId.value = classList[classList.length - 1]

  // 靶向班的情况
  if (classList[0] === 0) {
    // 所有的靶向班
    const targetClass = tbClassList.value.filter(item => item.value === 0)
    console.log(targetClass)
    // 查找靶向班的gradeId
    if (targetClass.length) {
      const findTargetClass = targetClass[0].children.find(
        item => classList[1] === item.value
      )
      currentGradeNum.value = findTargetClass.grade_num
      currentGradeId.value = findTargetClass.grade_id
      classType.value = findTargetClass.class_type
    }
  } else {
    currentGradeNum.value = classList[0]
    console.log(classList)
    const teachClass = tbClassList.value.filter(
      item => item.value === classList[0]
    )
    console.log(teachClass[0])
    const findTeachClass = teachClass[0].children.find(
      item => classList[1] === item.value
    )
    currentGradeId.value = teachClass[0].grade_id
    classType.value = findTeachClass.class_type
  }
  console.log(currentGradeId.value)
}

const findValue = (data, targetValue) => {
  if (Array.isArray(targetValue)) {
    targetValue = targetValue[targetValue.length - 1]
  }
  for (let item of data) {
    if (item.value === targetValue) {
      return true
    }

    if (item.children && item.children.length > 0) {
      const found = findValue(item.children, targetValue)
      if (found) {
        return true
      }
    }
  }

  return false
}

const changeSubject = async val => {
  console.log(val, isTargetBoost.value)

  if (isTargetBoost.value) {
    await nextTick()
    tbClassList.value = await getClassListOfSubject(val)
    if (!findValue(tbClassList.value, selectedClass.value)) {
      currentGradeNum.value = nowIsSmartRoomCode.value
        ? tbClassList.value[0]?.children[0]?.grade_num
        : tbClassList.value[0]?.value
      currentGradeId.value = nowIsSmartRoomCode.value
        ? tbClassList.value[0]?.children[0]?.grade_id
        : tbClassList.value[0]?.grade_id
      classId.value = tbClassList.value[0]?.children[0].value
      selectedClass.value = tbClassList.value[0]?.children[0].value
      classType.value = tbClassList.value[0]?.children[0].class_type
      console.log(currentGradeId.value)
    }
  }
  console.log(tbClassList.value)

  emit('changeSubject', val)
}

watch(
  () => [
    nowGlobalSubjectId.value,
    nowGlobalStageId.value,
    tbAdminAndTeachingClassList.value
  ],
  v => {
    changeSubject(v[0])
  },
  {
    immediate: true
  }
)

const transformToTreeSelectData = data => {
  console.log(data.admini_and_teaching_class)
  let adminiAndTeachingClass = []
  if (data.admini_and_teaching_class) {
    adminiAndTeachingClass = data.admini_and_teaching_class.map(school => ({
      label: '教学班',
      value: 2,
      children: school.grade_list.map(grade => ({
        label: grade.grade_name,
        value: grade.grade_id,
        id: grade.grade_num,
        children: grade.class_list.map(classItem => ({
          label: classItem.class_name,
          value: classItem.class_id
        }))
      }))
    }))
  }

  let targetedClass = []
  if (data.targeted_class) {
    targetedClass = data.targeted_class?.map(targetClass => ({
      label: targetClass.name,
      value: targetClass.class_id
    }))
    console.log(targetedClass)
  }

  return [...adminiAndTeachingClass, ...targetedClass]
}

onBeforeMount(async () => {
  await getTeachingInfo(nowGlobalRole.value.role_code)

  emit('changeSubject', nowGlobalSubjectId.value)

  if (isTargetBoost.value) {
    tbClassList.value = await getClassListOfSubject(nowGlobalSubjectId.value)
    console.log(tbClassList.value)
    if (!selectedClass.value) {
      selectedClass.value = tbClassList.value[0].children[0].value
      classId.value = tbClassList.value[0].children[0].value
      currentGradeNum.value = tbClassList.value[0].value
      currentGradeId.value = tbClassList.value[0].grade_id
    }
  } else {
    const classroomTree = await postClassroomTree(
      JSON.stringify({
        teacher_id: +userInfo.userId
      })
    )
    classroomData.value = transformToTreeSelectData(classroomTree.data)
    console.log(classroomData.value)
    // 默认选中第一个班级
    currentGradeNum.value = classroomData.value[0].children[0].id
    console.log(currentGradeNum.value)
    classId.value = classroomData.value[0].children[0].children[0].value
  }
})

const defaultDateRange = computed(() => {
  const today = new Date()
  const start = new Date(today.getFullYear(), today.getMonth(), 1)
  const end = new Date(today.getFullYear(), today.getMonth() + 1, 0)
  return [start, end]
})

const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0), // 设置为0点
  new Date(2000, 1, 1, 23, 59, 59) // 设置为23点59分59秒
]
const shortcuts = [
  {
    text: '近一个月',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date(end)
      start.setMonth(start.getMonth() - 1)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    }
  },
  {
    text: '近三个月',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date(end)
      start.setMonth(start.getMonth() - 3)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    }
  },
  {
    text: '近半年',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date(end)
      start.setMonth(start.getMonth() - 6)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    }
  },
  {
    text: '近一年',
    value: () => {
      const end = new Date()
      end.setHours(23, 59, 59, 999)
      const start = new Date(end)
      start.setFullYear(start.getFullYear() - 1)
      start.setHours(0, 0, 0, 0)
      return [start, end]
    }
  }
]
</script>
<style lang="less" scoped>
.selector {
  display: flex;
  gap: 20px;
  margin-bottom: 22px;
  position: relative;
  font-size: @size-big;

  .select-items {
    width: 92px;
  }

  .date {
    width: 388px;
    :deep(.el-date-editor) {
      width: 100%;
    }
  }

  :deep(.el-input),
  :deep(.el-select__wrapper),
  :deep(.el-date-editor .el-range-input) {
    font-size: @size-big;
  }

  :deep(.el-input__wrapper) {
    box-shadow: none;
  }
}
</style>
